from flask import Blueprint,request,jsonify
import json,datetime
from db import db
import math
good_bp = Blueprint('good_bp',__name__,url_prefix='/goods')

@good_bp.route('/cateM',methods=['POST','GET'])
def cateM():
    if request.method == 'POST':
        data = json.loads(request.data)
        userid = data['userid']
        type = data['type']
        name=data['name']
        sort = data['sort']
        ctime = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
        sql = "insert into category(type,name,sort,create_time,update_time,create_user,update_user) values (%d,'%s',%d,'%s','%s',%d,%d)"%(type,name,sort,ctime,ctime,userid,userid)
        print(sql)
        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "msg":'添加成功'
        })
    else:
        #一共有多少条
        sql = "select count(id) from category"
        res = db.find(sql)
        print('---',res)
        total = res['count(id)']
        #每页显示多少条
        page_size = 3
        # 当前第几页面
        page = request.args.get('page')
        page = int(request.args.get('page',1))
        # 计算总共有多少页
        tpage = math.ceil(total/page_size)
        # 获取当前页数据
        start = (page-1)*page_size
        sql1 = "select * from category limit %d,%d"%(start,page_size)
        tres=db.find_all(sql1)
        return jsonify({
            "code":200,
            "total":total,
            'page_size':page_size,
            'tpage':tpage,
            'list':tres
        })


# 上传图片
from projectcom import fileupload


@good_bp.route('/uploader',methods=['POST'])
def uploader():
    file = request.files.get('file')
    res = fileupload(file)
    return jsonify({
        "code":200,
        'url':res
    })

from utils.my_redis import r
# 分页接口代码
@good_bp.route('/dishM',methods=['POST','GET'])
def disM():
    if request.method=='GET':
        page_size = 2
        page = request.args.get('page')
        if not page:
            sql2 = "select id,name from dish"
            trs = db.find_all(sql2)
            return jsonify({
                "code":200,
                "list":trs
            })
        page = int(request.args.get('page',1))
        sql1 = "select count from dish"
        rs = db.find_all(sql1)
        total = rs['count']
        if page>=1:
            # 从redis中查询上一页最大值，如果没有存在redis
            pre = page-1
            max = r.get_str('dish'+str(pre))
            if max:
                sql = "select * from dish where id>%d limit 0,%d"%(int(max),page_size)
            else:
                statr = (int(page)-1)*page_size
                sql = "select * from dish limit %d,%d"%(statr,page_size)
            res = db.find_all(sql)
            r.set_str('dish'+str(page),str(res[-1:][0]['id']))
        return jsonify({
            "code":200,
            'total':total,
            'page_size':page_size,
            'list':res
        })
    else:
        # 获取参数
        data = json.loads(request.data)
        create_time = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d %H:%M:%S")
        upadte_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        # 添加菜品
        sql = "insert into dish(name,category_id,price,code,image,create_time,update_time,create_user,update_user)" \
              "values ('%s',%d,'%s','%s','%s','%s','%s',%d,%d)"%(data['name'],data['category_id'],data['price'],data['code'],data['image'],create_time,upadte_time,data['cuser'],data['u_user'])
        # 加入数据库
        db.update(sql)
        db.commit()
        # 清除分页缓存
        r.removeall_str('dish')
        return jsonify({
            'code':200,
            "msg":'添加菜品成功'
        })

# 套餐添加接口
@good_bp.route('/setM',methods=['POST','PUT'])
def setM():
    if request.method=='POST':
        data = json.loads(request.data)
        create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        upadte_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
        sql = "insert into setmeal(category_id,name,price,image,create_time,update_time,create_user,update_user)" \
              "values (%d,'%s','%s','%s','%s','%s',%d,%d)"%(data['category_id'],data['name'],data['price'],data['image'],create_time,upadte_time,data['cuser'],data['u_user'])
        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "mag":'添加成功'
        })
    else:
        set_id = request.args.get('set_id')
        data = json.loads(request.data)
        if data['category_id']:
            sql = "update setmeal set category_id=%d where id=%d"%(data['category_id'],set_id)
        if data['name']:
            sql = "update setmeal set name='%s' where id=%d" % (data['name'],set_id)
        if data['price']:
            sql = "update setmeal set price='%s' where id=%d" % (data['price'],set_id)
        if data['image']:
            sql = "update setmeal set image='%s where id=%d'" % (data['image'],set_id)

        db.update(sql)
        db.commit()
        return jsonify({
            "code":200,
            "msg":'修改成功'
        })
